package com.by.basicweb.config;

import lombok.extern.slf4j.Slf4j;
import org.dromara.dynamictp.core.support.ExecutorAdapter;
import org.dromara.dynamictp.core.support.ExecutorWrapper;
import org.dromara.dynamictp.starter.adapter.webserver.undertow.UndertowDtpAdapter;
import org.jboss.threads.EnhancedQueueExecutor;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Configuration
public class UndertowWorkersPreStartConfig {

    @Resource
    private UndertowDtpAdapter undertowDtpAdapter;

    @EventListener(ApplicationStartedEvent.class)
    public void initConsumers(ApplicationStartedEvent event) {
        if (Objects.isNull(undertowDtpAdapter)) {
            return;
        }

        Map<String, ExecutorWrapper> executorWrappers = undertowDtpAdapter.getExecutorWrappers();
        if (Objects.isNull(executorWrappers) || executorWrappers.isEmpty()) {
            return;
        }

        ExecutorWrapper undertowTp = executorWrappers.get("undertowTp");
        if (Objects.isNull(undertowTp)) {
            return;
        }

        ExecutorAdapter<?> executor = undertowTp.getExecutor();
        if (Objects.isNull(executor)) {
            return;
        }

        if (!(executor.getOriginal() instanceof EnhancedQueueExecutor oriExecutor)) {
            return;
        }

        // 初始化所有核心线程
        int initCorePoolSize = oriExecutor.prestartAllCoreThreads();

        log.info("[UndertowWorkersRunner][run] preStartAllCoreThreadsSuccess:[{}]", initCorePoolSize);
    }

}
